/**
 *
 * @Author 董熠涛
 * @Date 2025/6/16 20:22
 */
package example.springboot.service;

import example.springboot.dto.ChartDataDTO;
import example.springboot.dto.StatisticsDTO;
import example.springboot.mapper.StatisticsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class StatisticsService {

    @Autowired
    private StatisticsMapper statisticsMapper;

    /**
     * 获取统计数据
     */
    public StatisticsDTO getStatistics() {
        StatisticsDTO dto = new StatisticsDTO();
        dto.setTotalUsers(statisticsMapper.countTotalUsers());
        dto.setTotalWords(statisticsMapper.countTotalWords());
        dto.setTotalWordbooks(statisticsMapper.countTotalWordbooks());
        dto.setTotalStudyRecords(statisticsMapper.countTotalStudyRecords());
        return dto;
    }

    /**
     * 获取用户增长趋势
     */
    public List<ChartDataDTO> getUserGrowthTrend(int days) {
        List<ChartDataDTO> dbData = statisticsMapper.getUserGrowthTrend(days);
        return fillMissingDates(dbData, days);
    }

    /**
     * 获取学习活跃度趋势
     */
    public List<ChartDataDTO> getStudyActivityTrend(int days) {
        List<ChartDataDTO> dbData = statisticsMapper.getStudyActivityTrend(days);
        return fillMissingDates(dbData, days);
    }

    /**
     * 填充缺失的日期，确保返回完整的日期序列
     */
    private List<ChartDataDTO> fillMissingDates(List<ChartDataDTO> data, int days) {
        // 创建日期到数量的映射
        Map<String, Integer> dataMap = data.stream()
                .collect(Collectors.toMap(ChartDataDTO::getDate, ChartDataDTO::getCount));

        // 生成完整的日期列表
        List<ChartDataDTO> result = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate today = LocalDate.now();

        for (int i = days - 1; i >= 0; i--) {
            LocalDate date = today.minusDays(i);
            String dateStr = date.format(formatter);
            Integer count = dataMap.getOrDefault(dateStr, 0);
            result.add(new ChartDataDTO(dateStr, count));
        }

        return result;
    }
}

